package com.zzx.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * @version 1.0
 * @Author ZZX
 * @Date 2023/10/3 23:37
 */
@Slf4j
@Tag(name = "系统控制器", description = "系统模块")
@RestController
@RequestMapping("/sys")
public class SysController
{
    /**
     * DiscoveryClient 可以用来获取一些配置的信息，得到具体的微服务！
     */
    @Resource
    private DiscoveryClient client;

    @Value("${spring.application.name}")
    private String instanceName;

    /**
     * 获取一些注册进来的微服务的信息~，
     *
     * @return
     */
    @Tag(name = "系统控制器")
    @ApiOperation("获取微服务列表")
    @GetMapping("/discovery")
    @HystrixCommand(fallbackMethod = "discoveryFallback")
    public Object discovery()
    {
        // 获取微服务列表的清单
        List<String> services = client.getServices();
        log.info("discovery=>services:" + services);
        // 得到一个具体的微服务信息,通过具体的微服务id，applicaioinName；
        List<ServiceInstance> instances = client.getInstances(instanceName);
        for (ServiceInstance instance : instances)
        {
            log.info(
                    "ip:" + instance.getHost() + "\tport:" + // 主机名称
                            instance.getPort() + "\turl:" + // 端口号
                            instance.getUri() + "\tserver-id:" + // uri
                            instance.getServiceId() // 服务id
            );
        }
        return this.client;
    }

    public Object discoveryFallback()
    {
        return this.client;
    }

}